import { mockOrganizationTreeData, mockUsers } from "../mock/data/treeData";
import { Organization } from "../types/user";
import { PaginationParams } from "../types/api";
import http from "./http";
import { DEFAULT_API_PREFIX } from "@/constants/index";
// 是否使用 mock接口
const useMock = true;

/**
 * 扁平化组织架构树数据
 * @param data 组织架构树数据
 * @returns 扁平化后的组织架构数据
 */
const flattenOrganizationTreeData = (data: Organization[]) => {
  const result: Organization[] = [];

  const flatten = (nodes: Organization[], parentId?: number) => {
    nodes.forEach((node) => {
      const newNode = { ...node, parentId };
      result.push(newNode);
      if (node.children) {
        flatten(node.children, node.orgId);
      }
    });
  };

  flatten(data);
  return result;
};

/**
 * 团队人员服务（Mock 数据）
 */
const teamServiceMock = {
  /**
   * 获取组织架构树（模拟数据）
   * @returns 模拟的组织架构树数据
   */
  getOrganizationTree(): Promise<any[]> {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(mockOrganizationTreeData);
      }, 800);
    });
  },

  /**
   * 根据组织 ID 获取其下的所有成员和部门（模拟数据）
   * @param id 组织 ID
   * @param flatData 扁平化的组织架构数据
   * @returns 模拟的成员和部门数据
   */
  getOrganizationTreeById: (
    id: number,
    flatData: Organization[]
  ): Promise<any[]> => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const orgTree = flatData
          .filter((org) => org.parentId === id)
          .map((org) => {
            delete org.children; // 删除 children 属性
            return { ...org, id: org.orgId, isOrg: true };
          });

        const users = mockUsers
          .filter((user) => user.orgId === id)
          .map((user) => {
            return { ...user, parentId: id, isOrg: false };
          });

        resolve([...orgTree, ...users]);
      }, 800);
    });
  },

  /**
   * 根据组织 ID 获取其下的所有成员（模拟数据）
   * @param id 组织 ID
   * @returns 模拟的成员数据
   */
  getOrganizationTreeByOrgPath: (id: number): Promise<any[]> => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const users = mockUsers
          .filter((user) => user.orgId === id)
          .map((user) => {
            return { ...user, parentId: id, isOrg: false };
          });

        resolve(users);
      }, 800);
    });
  },
  /**
   * 获取已添加的成员（模拟数据，仅返回奇数 ID 的用户）
   * @returns 模拟的已添加成员数据
   */
  getAddedMembers: () => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(mockUsers.filter((user) => user.id % 2 === 1));
      }, 800);
    });
  },

  /**
   * 分页查询人员（支持关键字过滤，模拟数据）
   * @param params 分页参数
   * @returns 模拟的分页人员数据
   */
  getUsers: (params: PaginationParams) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const { page_num, page_size, keyword } = params;

        const filtered = keyword
          ? mockUsers.filter((user) =>
              user.name.toLowerCase().includes(keyword.toLowerCase())
            )
          : mockUsers;

        if (!page_num || !page_size) {
          resolve(filtered);
          return;
        }

        const start = (page_num - 1) * page_size;
        const end = start + page_size;
        resolve({ users: filtered.slice(start, end) });
      }, 800);
    });
  },

  // 批量添加空间团队成员
  addSpaceMembers: (params: { userIdList: number[]; spaceId: number }) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({ success: true, params });
      }, 800);
    });
  },

  // 单个删除空间团队成员
  deleteSpaceMember: (params: { id: number; spaceId: number }) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({ success: true, params });
      }, 800);
    });
  },
};

/**
 * 团队人员服务（真实接口）
 */
const teamService = {
  /**
   * 获取组织架构树
   * @returns 组织架构树数据
   */
  getOrganizationTree: () => {
    return http.get(`${DEFAULT_API_PREFIX}/console/org/tree`);
  },

  /**
   * 根据组织 ID 获取其下的所有成员和部门
   * @param id 组织 ID
   * @returns 成员和部门数据
   */
  getOrganizationTreeById: (id: number) => {
    return http.get(`${DEFAULT_API_PREFIX}/console/sys_user/list_by_org/${id}`);
  },
  /**
   * 根据组织 ID 获取其下的所有成员
   * @param id 组织 ID
   * @returns 成员和部门数据
   */
  getOrganizationTreeByOrgPath: (id: number) => {
    return http.get(
      `${DEFAULT_API_PREFIX}/console/sys_user/list_by_org_path/${id}`
    );
  },
  /**
   * 获取已添加的成员
   * @param id 空间 ID
   * @returns 已添加成员数据
   */
  getAddedMembers: (id: number) => {
    return http.get(`${DEFAULT_API_PREFIX}/console/space/user/selected/${id}`);
  },

  /**
   * 分页查询人员
   * @param params 分页参数
   * @returns 分页人员数据
   */
  getUsers: (params: PaginationParams) => {
    return http.get(`${DEFAULT_API_PREFIX}/console/sys_user/search`, {
      params,
    });
  },

  /**
   * 批量添加空间团队成员
   * @param params 添加参数
   * @returns 添加结果
   */
  addSpaceMembers: (params: { userIdList: number[]; spaceId: number }) => {
    return http.post(`${DEFAULT_API_PREFIX}/console/space/user/add`, params);
  },
  /**
   * 单个删除空间团队成员
   * @param params 删除参数
   * @return 删除结果
   * */
  deleteSpaceMember: (params: { id: number; spaceId: number }) => {
    return http.post(`${DEFAULT_API_PREFIX}/console/space/user/delete`, params);
  },
};

export default useMock ? teamServiceMock : teamService;

export { flattenOrganizationTreeData };
